package com.xpm.adapter.simple;

import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.xpm.R;
import com.xpm.entity.ItemBean;

import java.util.List;

public abstract class RecycleViewBaseAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    private final List<ItemBean> mData;
    private  OnItemClickListener onItemClickListener;

    public RecycleViewBaseAdapter(List<ItemBean> datas){
        this.mData = datas;
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = View.inflate(parent.getContext(), getResourceId(), null);
        return new RecycleViewBaseAdapter.InnerHolder(view);
    }

    /**
     * item 布局资源
     * @return
     */
    protected abstract int getResourceId();

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
        ((RecycleViewBaseAdapter.InnerHolder)holder).setData(mData.get(position),position);
    }

    @Override
    public int getItemCount() {
        return mData == null?0:mData.size();
    }

    /***
     * 设置条目点击事件
     * 设置回调接口
     * 1.1 创建创建接口
     * 1.2 定义接口内部的方法
     * 1.3 提供设置接口的方法（其实是外部接口的调用）
     * 1.4 接口方法的调用
     */
    public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
        this.onItemClickListener = onItemClickListener;
    }

    public interface OnItemClickListener{
        void onItemClick(int position);
    }


    public class InnerHolder extends RecyclerView.ViewHolder {
        private ItemBean mItemBean;
        private ImageView iv_icon;
        private TextView tv_title;
        private int position;

        public InnerHolder(@NonNull View itemView) {
            super(itemView);
            iv_icon = itemView.findViewById(R.id.iv_icon);
            tv_title = itemView.findViewById(R.id.tv_title);

            if(onItemClickListener != null){
                itemView.setOnClickListener(v -> {
                    onItemClickListener.onItemClick(position);
                });
            }


        }
        public void setData(ItemBean itemBean,int position) {
            this.mItemBean = itemBean;
            this.position = position;
            iv_icon.setImageResource(this.mItemBean.icon);
            tv_title.setText(this.mItemBean.title);
        }
    }
}
